import 'dart:io';

import 'package:auto_size_text/auto_size_text.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:furaha_mkopo/commonTool/fm_jump_tool.dart';
import 'package:furaha_mkopo/commonTool/fm_language_tool.dart';
import 'package:furaha_mkopo/commonTool/fm_route_tool.dart';
import 'package:furaha_mkopo/commonTool/fm_screen_tool.dart';
import 'package:furaha_mkopo/commonTool/fm_time_tool.dart';
import 'package:furaha_mkopo/commonUI/fm_life_visibility_page.dart';
import 'package:furaha_mkopo/page/authentication/dialog/fm_auth_info_confirm_dialog.dart';
import 'package:furaha_mkopo/page/authentication/dialog/fm_id_card_base_dialog.dart';
import 'package:furaha_mkopo/page/authentication/dialog/fm_id_card_dialog.dart';
import 'package:furaha_mkopo/page/authentication/dialog/fm_id_card_nida_dialog.dart';
import 'package:furaha_mkopo/page/authentication/dialog/fm_id_card_other_dialog.dart';
import 'package:furaha_mkopo/page/authentication/dialog/fm_id_card_voter_dialog.dart';
import 'package:furaha_mkopo/page/authentication/entity/fm_identity_authentication_entity.dart';
import 'package:furaha_mkopo/page/authentication/enum/fm_auth_select_enum.dart';
import 'package:furaha_mkopo/page/authentication/enum/fm_authentication_enum.dart';
import 'package:furaha_mkopo/page/authentication/fm_auth_controller.dart';
import 'package:furaha_mkopo/page/base/fm_base_page_widget.dart';
import 'package:furaha_mkopo/page/home/controller/fm_common_controller.dart';
import 'package:geolocator_platform_interface/src/models/position.dart';
import 'package:get/get.dart';

class FMIdentityAuthPage extends FMBasePageWidget {
  String listen;
  bool? isOldPage;

  FMIdentityAuthPage({super.key, required this.listen,this.isOldPage});

  @override
  State<FMIdentityAuthPage> createState() => _FMIdentityAuthPageState();
}

class _FMIdentityAuthPageState extends FMBasePageState<FMIdentityAuthPage> {
  final controller = Get.put(FMAuthController());
  final commonController = Get.put(FMCommonController());
  FMAuthSelectEnum selectEnum = FMAuthSelectEnum.nida;

  @override
  void initState() {
    super.initState();
    controller.requestData(widget.listen);
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<FMAuthController>(
      builder: (controller) {
        return Container(
          color: const Color(0xFF54E04E),
          child: Column(
            children: [
              SizedBox(
                height: FMScreenTool.topPadding(context),
              ),
              generateTitle(context),
              Expanded(
                child: SingleChildScrollView(
                  child: Container(
                    height: FMScreenTool.height(context) + 54,
                    width: FMScreenTool.width(context),
                    alignment: Alignment.center,
                    child: Stack(
                      fit: StackFit.expand,
                      children: [
                        Positioned(
                          top: 14,
                          left: 16,
                          right: 16,
                          child: Container(
                            height: 402,
                            decoration: const BoxDecoration(
                              borderRadius: BorderRadius.all(Radius.circular(16)),
                              gradient: LinearGradient(
                                  begin: Alignment.topCenter,
                                  end: Alignment.bottomCenter,
                                  colors: [Color(0xFFE6FFD6), Colors.white]),
                            ),
                            child: Column(
                              children: [
                                generateStep(context),
                                const SizedBox(
                                  height: 13,
                                ),
                                generateContent(),
                              ],
                            ),
                          ),
                        ),
                        Positioned(
                            top: 400,
                            left: 16,
                            right: 16,
                            child: generateFace(context)),
                        Positioned(
                            top: 400 + 204 + 43,
                            left: 16,
                            right: 16,
                            child: generateNext()),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
        );
      }
    );
  }

  Widget generateTitle(BuildContext context) {
    String title = FMLanguageTool.getText("Identity authentication");
    return SizedBox(
      height: 44,
      width: double.infinity,
      child: Stack(
        children: [
          Positioned(
              left: 18,
              top: 0,
              bottom: 0,
              child: GestureDetector(
                  behavior: HitTestBehavior.translucent,
                  onTap: () {
                    FMRouteTool.pop(context);
                  },
                  child: Image.asset("assets/images/back.png",
                      width: 24, height: 24))),
          Positioned(
              left: 0,
              top: 0,
              bottom: 0,
              right: 0,
              child: Container(
                alignment: Alignment.center,
                child: Text(
                  title,
                  style: const TextStyle(
                      fontSize: 16,
                      color: Color(0xFF333333),
                      fontWeight: FontWeight.w600,
                      decoration: TextDecoration.none),
                ),
              )),
        ],
      ),
    );
  }

  Widget generateStep(BuildContext context) {
    return Container(
      height: 80,
      width: 320,
      margin: const EdgeInsets.only(left: 11, right: 11, top: 12),
      child: Column(
        children: [
          Container(
            alignment: Alignment.center,
            height: 80,
            width: double.infinity,
            padding: const EdgeInsets.only(left: 17, right: 17),
            decoration: const BoxDecoration(
                image: DecorationImage(
                    image:
                        AssetImage("assets/authentication/ic_sfrz_step_bg.png"),
                    fit: BoxFit.fill)),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  FMLanguageTool.getText("Step1"),
                  style: const TextStyle(
                      fontSize: 18,
                      color: Colors.black,
                      decoration: TextDecoration.none,
                      fontWeight: FontWeight.w700),
                ),
                const SizedBox(
                  height: 4,
                ),
                AutoSizeText(
                  FMLanguageTool.getText("Please fill in your information truthfully"),
                  maxFontSize: 14,
                  minFontSize: 5,
                  maxLines: 1,
                  style: const TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w500,
                      decoration: TextDecoration.none,
                      color: Color(0xFF614815)),
                )
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget generateContent() {
    return Container(
      width: 320,
      height: 271,
      decoration: BoxDecoration(
        borderRadius: const BorderRadius.all(Radius.circular(12)),
        border: Border.all(color: const Color(0xFF6ACB6B), width: 1.5),
        gradient: const LinearGradient(
            begin: Alignment.centerLeft,
            end: Alignment.centerRight,
            colors: [Color(0xFFC9FDC9), Colors.white]),
      ),
      child: GetBuilder<FMAuthController>(
        id: "fm_content",
        builder: (controller) {
          return Column(
            children: [
              Container(
                height: 56,
                width: double.infinity,
                margin: const EdgeInsets.only(left: 10, right: 10, top: 12),
                padding: const EdgeInsets.only(left: 16, right: 16),
                alignment: Alignment.center,
                decoration: const BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(12)),
                    color: Color(0xFF54E041)),
                child: AutoSizeText(
                  FMLanguageTool.getText("Please select ont of the following documents to upload"),
                  maxFontSize: 16,
                  minFontSize: 5,
                  maxLines: 2,
                  style: const TextStyle(
                      fontSize: 16,
                      color: Color(0xFF333333),
                      fontWeight: FontWeight.w400,
                      decoration: TextDecoration.none),
                ),
              ),
              generateBottomContent()
            ],
          );
        }
      ),
    );
  }

  Widget generateFace(BuildContext context) {
    return Container(
      height: 204,
      width: double.infinity,
      alignment: Alignment.bottomCenter,
      decoration: const BoxDecoration(
          image: DecorationImage(
              image: AssetImage("assets/authentication/ic_sfrz_face_bg.png"),
              fit: BoxFit.fill)),
      child: Container(
          height: 137,
          margin: const EdgeInsets.only(left: 11, right: 11, bottom: 11),
          padding: const EdgeInsets.only(left: 16, right: 16),
          decoration: BoxDecoration(
            borderRadius: const BorderRadius.all(Radius.circular(12)),
            gradient: const LinearGradient(
              begin: Alignment.centerLeft,
              end: Alignment.centerRight,
              colors: [Color(0xFFC9FDC9), Colors.white],
            ),
            border: Border.all(color: const Color(0xFF6ACB6B), width: 1.5),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    controller.voice?.silently??"",
                    style: const TextStyle(
                        fontSize: 16,
                        color: Color(0xFF333333),
                        decoration: TextDecoration.none,
                        fontWeight: FontWeight.w700),
                  ),
                  const SizedBox(
                    height: 10,
                  ),
                  generateImage(controller.voice?.embraced??"", FMAuthenticationEnum.face),
                ],
              ),
              generateUploadOrCompleted(context,
                  controller.voice?.embraced ?? "", FMAuthenticationEnum.face)
            ],
          )),
    );
  }

  Widget generateNext() {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: (){

        if (widget.isOldPage == true) {
          Navigator.pop(context);
          return;
        }

        bool isIncomplete = handleIncomplete();
        if(isIncomplete){
          // TODO
          commonController.onRequestNoEmptyListen(context,widget.listen);
        }else {
          controller.faceTime = FMTimeTool.currentTime;
          FMIdCardBaseDialog.showCardDialog(
              context, getType(), selectEnum, onSelectImage);
        }
      },
      child: Container(
          height: 46,
          width: double.infinity,
          decoration: const BoxDecoration(
              image: DecorationImage(
                  image: AssetImage("assets/authentication/ic_sfrz_next_bg.png"),
                  fit: BoxFit.fill)),
          child: Center(
              child: Text(FMLanguageTool.getText("Next"),
                  style: const TextStyle(
                      fontSize: 18,
                      color: Colors.white,
                      decoration: TextDecoration.none,
                      fontWeight: FontWeight.w700)))),
    );
  }

  Widget generateBottomContent(){
    if(controller.voice?.furious != null && controller.voice?.furious != ""){
      return generateCompleted(controller.voice?.card_type??"");
    }else {
      return Column(
        children: [
          generateNIDA(),
          generateVoter(),
          generateOther()
        ],
      );
    }
  }

  Widget generateNIDA(){
    String url = controller.voice?.furious??"";
    return Column(
      children: [
        const SizedBox(
          height: 8,
        ),
        generateRowWidget(FMLanguageTool.getText("NIDA（CITIZEN IDENTITY CARD）"), FMAuthSelectEnum.nida),
        Visibility(
          visible: selectEnum == FMAuthSelectEnum.nida,
          child: Container(
            margin: const EdgeInsets.only(left: 16, right: 16,top: 8),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                generateImage(url, FMAuthenticationEnum.idCardFont),
                generateUploadOrCompleted(context, url, FMAuthenticationEnum.idCardFont)
              ],
            ),
          ),
        ),
        const SizedBox(
          height: 2,
        ),
      ],
    );
  }

  Widget generateVoter(){
    String url = controller.voice?.furious??"";
    return Column(
      children: [
        const SizedBox(
          height: 8,
        ),
        generateRowWidget(FMLanguageTool.getText("Voter Card（KADI YA MPIGA KURA）"), FMAuthSelectEnum.voter),
        Visibility(
          visible: selectEnum == FMAuthSelectEnum.voter,
          child: Container(
            margin: const EdgeInsets.only(left: 16, right: 16,top: 8),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                generateImage(url, FMAuthenticationEnum.idCardFont),
                generateUploadOrCompleted(context, url, FMAuthenticationEnum.idCardFont)
              ],
            ),
          ),
        ),
        const SizedBox(
          height: 8,
        ),
      ],
    );
  }

  Widget generateOther(){
    String url = controller.voice?.furious??"";
    return Visibility(
      visible: controller.voice?.display_other == 1,
      child: Column(
        children: [
          generateRowWidget(FMLanguageTool.getText("Other"), FMAuthSelectEnum.other),
          Visibility(
            visible: selectEnum == FMAuthSelectEnum.other,
            child: Container(
              margin: const EdgeInsets.only(left: 16, right: 16),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  generateImage(url, FMAuthenticationEnum.idCardFont),
                  generateUploadOrCompleted(context, url, FMAuthenticationEnum.idCardFont)
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget generateCompleted(String text){
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const SizedBox(
          height: 8,
        ),
        Container(
          margin: const EdgeInsets.only(left: 16, right: 16),
          child: AutoSizeText(
            text,
            maxLines: 1,
            maxFontSize: 14,
            minFontSize: 5,
            style: const TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w600,
                decoration: TextDecoration.none,
                color: Color(0xFF333333)),
          ),
        ),
        Container(
          margin: const EdgeInsets.only(left: 16, right: 16,top: 8),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              generateImage(controller.voice?.furious??"", FMAuthenticationEnum.idCardFont),
              generateUploadOrCompleted(context, controller.voice?.furious??"", FMAuthenticationEnum.idCardFont)
            ],
          ),
        ),
        const SizedBox(
          height: 8,
        ),
      ],
    );
  }

  Widget generateRowWidget(String text,FMAuthSelectEnum selectEnum) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        if(this.selectEnum == selectEnum){
          return;
        }
        this.selectEnum = selectEnum;
        controller.update(["fm_content"]);
      },
      child: Row(
        children: [
          const SizedBox(
            width: 16,
          ),
          Image.asset(
            selectEnum == this.selectEnum
                ? "assets/authentication/ic_auth_select.png"
                : "assets/authentication/ic_auth_no_select.png",
            width: 24,
            height: 24,
          ),
          const SizedBox(
            width: 2,
          ),
          Expanded(
            child: AutoSizeText(
              text,
              maxLines: 1,
              maxFontSize: 14,
              minFontSize: 5,
              style: const TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w600,
                  decoration: TextDecoration.none,
                  color: Color(0xFF333333)),
            ),
          ),
          const SizedBox(
            width: 16,
          ),
        ],
      ),
    );
  }

  Widget generateImage(String imagePath, FMAuthenticationEnum type) {
    String defaultImage = "";
    switch (type) {
      case FMAuthenticationEnum.idCardFont:
        if(selectEnum == FMAuthSelectEnum.nida){
          defaultImage = "assets/authentication/ic_sfrz_id_nida_card.png";
        }else if(selectEnum == FMAuthSelectEnum.voter){
          defaultImage = "assets/authentication/ic_sfrz_id_voter_card.png";
        }else {
          defaultImage = "assets/authentication/ic_sfrz_id_card.png";
        }
        break;
      case FMAuthenticationEnum.idCardBack:
        defaultImage = "assets/authentication/ic_sfrz_id_card_back.png";
        break;
      case FMAuthenticationEnum.face:
        defaultImage = "assets/authentication/ic_sfrz_face.png";
        break;
      default:
        break;
    }
    if (imagePath.isEmpty) {
      return Image.asset(
        defaultImage,
        width: 125,
        height: 87,
      );
    } else {
      return CachedNetworkImage(
        width: 125,
        height: 87,
        imageUrl: imagePath,
        fit: BoxFit.cover,
        placeholder: (context, url) => Image.asset(
          defaultImage,
          width: 125,
          height: 87,
        ),
        errorWidget: (context, url, error) => Image.asset(
          defaultImage,
          width: 125,
          height: 87,
        ),
      );
    }
  }

  Widget generateUploadOrCompleted(
      BuildContext context, String imagePath, FMAuthenticationEnum type) {
    if (imagePath.isEmpty) {
      return GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () async {
          controller.faceTime = FMTimeTool.currentTime;
          FMIdCardBaseDialog.showCardDialog(
              context, getType(), selectEnum, onSelectImage);
        },
        child: Image.asset(
          FMLanguageTool.getAssets("assets/authentication/ic_sfrz_upload"),
          width: 102,
          height: 42,
        ),
      );
    } else {
      return Image.asset(
        "assets/authentication/ic_sfrz_completed.png",
        width: 40,
        height: 40,
      );
    }
  }

  void onSelectImage(File? value,FMAuthenticationEnum type,FMAuthSelectEnum selectEnum,String alighted){
    if(value != null){
      controller.uploadImage(value, type,selectEnum, alighted,onAuthCallBack);
    }else {
      // FMToast.showText('Selection failed, please try again');
    }
  }

  void onAuthCallBack(FMAuthenticationEnum type,FMAuthImageResultEntity? resultEntity){
    if(type == FMAuthenticationEnum.idCardFont && resultEntity != null){
      showDialog(context: context, builder: (context){
        return FMAuthInfoConfirmDialog(resultEntity: resultEntity,listen: widget.listen,onConfirm: (){
          controller.reportRisk("2",controller.startTime);
          controller.onRefreshPage(widget.listen);
        },cardType: selectEnum.title,);
      });
    }else {
      if(type == FMAuthenticationEnum.idCardBack){
        controller.reportRisk("3",controller.startTime);
      }else if(type == FMAuthenticationEnum.face){
        controller.reportRisk("4",controller.faceTime);
      }
      controller.onRefreshPage(widget.listen);
    }
  }

  FMAuthenticationEnum getType(){
    String first = controller.voice?.furious??"";
    String three = controller.voice?.embraced??"";
    if(first.isEmpty){
      return FMAuthenticationEnum.idCardFont;
    }
    if(three.isEmpty){
      return FMAuthenticationEnum.face;
    }
    return FMAuthenticationEnum.complete;
  }

  bool handleIncomplete(){
    switch(getType()){
      case FMAuthenticationEnum.idCardFont:
        return false;
      case FMAuthenticationEnum.face:
        return false;
      default:
        return true;
    }
  }

  @override
  void onLocationError(String error) {
    // TODO: implement onLocationError
  }

  @override
  void onLocationUpdated(Position position) {
    controller.position = position;
  }
}
